package util;

import entity.User;

import java.sql.*;

/**
 * 数据库操作工具类
 */

public class MysqlUtil {
    private static final String url = "jdbc:mysql://localhost:3306/chat?ServerTimezone=Asia/Shanghai";
    private static final String username="root";
    private static final String password="123456";
    private static final String jdbc="com.mysql.cj.jdbc.Driver";
    /**
     * 查询是否存在用户
     * @param user 用户
     */
    public static boolean QueryUser(User user) throws ClassNotFoundException, SQLException {
        Connection conn= DriverManager.getConnection(url,username,password);
        Class.forName(jdbc);
        String sql="select * from user where username=? and password=?";
        PreparedStatement ps=conn.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ResultSet rs=ps.executeQuery();
        if(rs.next()){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 更改用户的在线状态
     * @param user 用户
     * @return
     */
    public static void UpdateOnline(User user,int num) throws SQLException, ClassNotFoundException {
        Connection conn=DriverManager.getConnection(url,username,password);
        Class.forName(jdbc);
        String sql="update user set isOnline=? where username=?";
        PreparedStatement ps=conn.prepareStatement(sql);
        ps.setInt(1,num);
        ps.setString(2,user.getUsername());
        ps.executeUpdate();
    }
}
